import json
import re

from django.contrib.auth import login
from django.shortcuts import render

# Create your views here.
from QQLoginTool.QQtool import OAuthQQ
from django.http import JsonResponse
from django_redis import get_redis_connection

from apps.oauth.models import OAuthQQUser
from apps.users.models import User
from meiduo_mall import settings
from django.views import View
from utlis.secret_key import *


# ****************************************
# 生成用户绑定链接
class QQAuthURLView(View):

    def get(self, request):
        next = request.GET.get('next')
        # 1. 生成OAuthQQ实例对象
        qq = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                     client_secret=settings.QQ_CLIENT_SECRET,
                     redirect_uri=settings.QQ_REDIRECT_URI,
                     state=next)
        login_url = qq.get_qq_url()
        return JsonResponse({'code': 0, 'errmsg': 'ok', 'login_url': login_url})


# ******************************
# 认证获取openid
# 获取code，通过code换取token，再通过token换取openid

class QQAuthUserView(View):
    def get(self, request):
        # 获取code
        code = request.GET.get('code')
        if code is None:
            return JsonResponse({'code': 0, 'errmsg': '参数不全'})
        # 通过code换取token
        qq = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                     client_secret=settings.QQ_CLIENT_SECRET,
                     redirect_uri=settings.QQ_REDIRECT_URI,
                     state='xxxx')
        token = qq.get_access_token(code)
        # 换取openid
        openid = qq.get_open_id(token)

        # 通过openid查询判断是否绑定了用户信息
        try:
            qquser = OAuthQQUser.objects.get(openid=openid)
        except OAuthQQUser.DoesNotExist:
            # 不存在 则需要绑定  返回openid
            # reponse = JsonResponse({'code':400,'access_token':openid})
            # return reponse

            # 对openid进行加密
            access_token = generate_access_token(openid)
            return JsonResponse({'code': 400, 'access_token': access_token})
        else:
            # 存在 绑定过直接登录
            # 设置session
            login(request, qquser.user)
            # 设置cookie
            reponse = JsonResponse({'code': 0, 'errmsg': 'ok'})
            reponse.set_cookie('username', qquser.user.username)
            return reponse

    def post(self, request):
        # 接收参数
        json_dict = json.loads(request.body.decode())
        mobile = json_dict.get('mobile')
        password = json_dict.get('password')
        sms_code = json_dict.get('sms_code')
        access_token = json_dict.get('access_token')

        # 校验参数
        if not all([mobile, password, sms_code]):
            return JsonResponse({'code': 400, 'errmsg': '参数不全'})

        # 判断手机号是否合法
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return JsonResponse({'code': 400,
                                 'errmsg': '请输入正确的手机号码'})

        # 判断密码是否合格
        if not re.match(r'^[0-9A-Za-z]{8,20}$', password):
            return JsonResponse({'code': 400,
                                 'errmsg': '请输入8-20位的密码'})

        # 校验短信验证码
        a = get_redis_connection('code')
        b = a.get(mobile)  # bytes
        if b is None:
            return JsonResponse({'code': 400, 'errmsg': '短信验证码失效'})
        if sms_code != b.decode():
            return JsonResponse({'code': 400, 'errmsg': '短信验证码有误'})

        # 获取解密后的openid
        openid = check_access_token(access_token)
        if openid is None:
            return JsonResponse({'code': 400, 'errmsg': '缺少openid'})

        try:
            # 根据手机号查询用户信息
            user = User.objects.get(mobile=mobile)
        except User.DoesNotExist:
            # 手机号不存在
            # 创建
            user = User.objects.create_user(username=mobile,
                                            mobile=mobile,
                                            password=password)
        else:
            # 手机号存在 验证密码是否正确
            if not user.check_password(password):
                return JsonResponse({'code': 400, 'errmsg': '账号或密码错误'})
        # 绑定
        OAuthQQUser.objects.create(user=user, openid=openid)

        login(request, user)

        reponse = JsonResponse({'code': 0, 'errmsg': 'ok'})
        reponse.set_cookie('username', user.username)

        return reponse
